<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../../stores/auth'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, VideoCamera, Warning, Key, Check } from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

// 控制显示登录、注册或忘记密码表单
const activeTab = ref('login')

const loginForm = ref({
  username: '',
  password: '',
  rememberMe: false
})

const registerForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

const loading = ref(false)

const handleLogin = async () => {
  if (!loginForm.value.username || !loginForm.value.password) {
    ElMessage.warning('请输入用户名和密码')
    return
  }

  loading.value = true
  try {
    // 判断输入的是邮箱还是用户名
    const isEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(loginForm.value.username)
    
    const loginData = {
      password: loginForm.value.password,
      remember: loginForm.value.rememberMe
    }
    
    // 根据输入类型设置不同的参数
    if (isEmail) {
      loginData.email = loginForm.value.username
    } else {
      loginData.username = loginForm.value.username
    }
    
    const result = await authStore.handleLogin(loginData)
    ElMessage.success(result.message || '登录成功')
    router.push('/dataManagement')
  } catch (error) {
    ElMessage.error(error.message || '登录失败，请重试')
  } finally {
    loading.value = false
  }
}

const handleRegister = async () => {
  if (!registerForm.value.username || !registerForm.value.email || !registerForm.value.password) {
    ElMessage.warning('请填写完整注册信息')
    return
  }

  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    ElMessage.warning('两次输入的密码不一致')
    return
  }

  loading.value = true
  try {
    await authStore.handleRegister({
      username: registerForm.value.username,
      email: registerForm.value.email,
      password: registerForm.value.password
    })
    ElMessage.success('注册成功，请登录')
    activeTab.value = 'login'
    // 清空注册表单
    registerForm.value = {
      username: '',
      email: '',
      password: '',
      confirmPassword: ''
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '注册失败，请重试')
  } finally {
    loading.value = false
  }
}

const switchTab = (tab) => {
  activeTab.value = tab
}

// 忘记密码相关
const resetForm = reactive({
  email: '',
  verificationCode: '',
  newPassword: '',
  confirmPassword: ''
})
const resetLoading = ref(false)
const showVerificationDialog = ref(false)
const verificationStep = ref(1) // 1: 发送验证码, 2: 输入新密码
const countdown = ref(0) // 验证码倒计时

// 切换到忘记密码表单
const openForgotPasswordForm = () => {
  // 重置表单
  resetForm.username = ''
  resetForm.email = ''
  resetForm.verificationCode = ''
  resetForm.newPassword = ''
  resetForm.confirmPassword = ''
  verificationStep.value = 1
  // 切换到忘记密码表单
  activeTab.value = 'forgotPassword'
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!resetForm.username) {
    ElMessage.warning('请填写用户名')
    return
  }
  if (!resetForm.email) {
    ElMessage.warning('请填写注册邮箱')
    return
  }

  resetLoading.value = true
  try {
    // 调用发送验证码的API
    const result = await authStore.handleSendVerificationCode({
      username: resetForm.username,
      email: resetForm.email
    })
    console.log("result "+result)
    if (result.data.code === 20000) {
      console.log(result)
      ElMessage.success(result.message || '验证码已发送，请查收邮件')
      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      console.error(result)
      throw new Error(result.message || '验证码发送失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error(error.message || '验证码发送失败，请重试')
  } finally {
    resetLoading.value = false
  }
}

// 验证验证码
const verifyCode = async () => {
  if (!resetForm.verificationCode) {
    ElMessage.warning('请输入验证码')
    return
  }

  resetLoading.value = true
  try {
    // 调用验证验证码的API
    const result = await authStore.handleVerifyCode({
      username: resetForm.username,
      email: resetForm.email,
      code: resetForm.verificationCode
    })
    verificationStep.value = 2
    ElMessage.success('验证码验证成功，请设置新密码')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '验证码验证失败，请重试')
  } finally {
    resetLoading.value = false
  }
}

// 重置密码
const resetPassword = async () => {
  if (!resetForm.newPassword || !resetForm.confirmPassword) {
    ElMessage.warning('请填写新密码')
    return
  }
  
  if (resetForm.newPassword !== resetForm.confirmPassword) {
    ElMessage.warning('两次输入的密码不一致')
    return
  }
  
  resetLoading.value = true
  try {
    // 调用重置密码API
    const result = await authStore.handleResetPassword({
      email: resetForm.email,
      code: resetForm.verificationCode,
      new_password: resetForm.newPassword,
      confirm_password: resetForm.confirmPassword
    })
    
    ElMessage.success(result.message || '密码重置成功')
    // 重置成功后切换回登录表单
    activeTab.value = 'login'
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '密码重置失败，请重试')
  } finally {
    resetLoading.value = false
  }
}
</script>

<template>
  <div class="auth-container">
    <div class="auth-box">
      <div class="auth-content">
        <div class="left-section">
          <div class="auth-header">
            <h1>智能漏洞入侵检测系统</h1>
            <p>全方位系统保护，实时预警，智能分析，守护您的网络安全</p>
          </div>
          <div class="features">
            <div class="feature-item">
              <div class="icon-container">
                <el-icon><VideoCamera /></el-icon>
              </div>
              <div class="feature-text">
                <h3>漏洞检测</h3>
                <p>实时检测系统薄弱环节，准确识别潜在入侵风险</p>
              </div>
            </div>
            <div class="feature-item">
              <div class="icon-container">
                <el-icon><Key /></el-icon>
              </div>
              <div class="feature-text">
                <h3>入侵防御</h3>
                <p>先进的AI防护技术，有效阻断恶意攻击，保障系统安全</p>
              </div>
            </div>
            <div class="feature-item">
              <div class="icon-container">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="feature-text">
                <h3>风险预警</h3>
                <p>多维度安全分析，及时预警潜在威胁</p>
              </div>
            </div>
          </div>
        </div>
        <div class="right-section">
          <div class="tabs">
            <span 
              class="tab" 
              :class="{ active: activeTab === 'login' }" 
              @click="switchTab('login')"
            >
              登录
            </span>
            <span 
              class="tab" 
              :class="{ active: activeTab === 'register' }" 
              @click="switchTab('register')"
            >
              注册
            </span>
            <span 
              class="tab" 
              :class="{ active: activeTab === 'forgotPassword' }" 
              @click="switchTab('forgotPassword')"
              v-if="activeTab === 'forgotPassword'"
            >
              忘记密码
            </span>
          </div>
          
          <div class="form-outer-container">
            <!-- 登录表单 -->
            <div v-if="activeTab === 'login'" class="auth-form login-form">
              <div class="form-item">
                <label>用户名/邮箱</label>
                <el-input
                  v-model="loginForm.username"
                  placeholder="请输入用户名或邮箱"
                  :prefix-icon="User"
                />
              </div>
              <div class="form-item">
                <label>密码</label>
                <el-input
                  v-model="loginForm.password"
                  type="password"
                  placeholder="请输入密码"
                  :prefix-icon="Lock"
                  show-password
                />
              </div>
              <div class="remember-me">
                <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
                <a href="javascript:void(0)" class="forgot-password" @click="openForgotPasswordForm">忘记密码？</a>
              </div>
              <el-button
                type="primary"
                class="submit-button"
                :loading="loading"
                @click="handleLogin"
              >
                登录
              </el-button>
            </div>
            
            <!-- 注册表单 -->
            <div v-if="activeTab === 'register'" class="auth-form register-form">
              <div class="form-item">
                <label>用户名</label>
                <el-input
                  v-model="registerForm.username"
                  placeholder="请输入用户名"
                  :prefix-icon="User"
                />
              </div>
              <div class="form-item">
                <label>邮箱</label>
                <el-input
                  v-model="registerForm.email"
                  type="email"
                  placeholder="请输入邮箱"
                  :prefix-icon="Message"
                />
              </div>
              <div class="form-item">
                <label>密码</label>
                <el-input
                  v-model="registerForm.password"
                  type="password"
                  placeholder="请输入密码"
                  :prefix-icon="Lock"
                  show-password
                />
              </div>
              <div class="form-item">
                <label>确认密码</label>
                <el-input
                  v-model="registerForm.confirmPassword"
                  type="password"
                  placeholder="请确认密码"
                  :prefix-icon="Lock"
                  show-password
                />
              </div>
              <el-button
                type="primary"
                class="submit-button"
                :loading="loading"
                @click="handleRegister"
              >
                注册
              </el-button>
            </div>
            
            <!-- 忘记密码表单 -->
            <div v-if="activeTab === 'forgotPassword'" class="auth-form forgot-password-form">
              <!-- 步骤1：输入用户名、邮箱和验证码 -->
              <template v-if="verificationStep === 1">
                <div class="form-item">
                  <label>用户名</label>
                  <el-input
                    v-model="resetForm.username"
                    placeholder="请输入用户名"
                    :prefix-icon="User"
                  />
                </div>
                <div class="form-item">
                  <label>邮箱</label>
                  <el-input
                    v-model="resetForm.email"
                    type="email"
                    placeholder="请输入注册邮箱"
                    :prefix-icon="Message"
                  />
                </div>
                <div class="form-item verification-code-item">
                  <label>验证码</label>
                  <div class="verification-code-input">
                    <el-input
                      v-model="resetForm.verificationCode"
                      placeholder="请输入验证码"
                      maxlength="6"
                    />
                    <el-button
                      type="primary"
                      class="send-code-button"
                      :loading="resetLoading"
                      :disabled="countdown > 0"
                      @click="sendVerificationCode"
                    >
                      {{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
                    </el-button>
                  </div>

                </div>
                <el-button
                  type="primary"
                  class="submit-button"
                  :loading="resetLoading"
                  @click="verifyCode"
                >
                  下一步
                </el-button>
              </template>

              <!-- 步骤2：输入新密码 -->
              <template v-if="verificationStep === 2">
                <div class="form-item">
                  <label>新密码</label>
                  <el-input
                    v-model="resetForm.newPassword"
                    type="password"
                    placeholder="请输入新密码"
                    :prefix-icon="Lock"
                    show-password
                  />
                </div>
                <div class="form-item">
                  <label>确认密码</label>
                  <el-input
                    v-model="resetForm.confirmPassword"
                    type="password"
                    placeholder="请确认新密码"
                    :prefix-icon="Lock"
                    show-password
                  />
                </div>
                <el-button
                  type="primary"
                  class="submit-button"
                  :loading="resetLoading"
                  @click="resetPassword"
                >
                  重置密码
                </el-button>
              </template>

              <div class="back-to-login">
                <a href="javascript:void(0)" @click="switchTab('login')">返回登录</a>
              </div>
            </div>


          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 忘记密码对话框已移除，改为内嵌表单 -->
</template>

<style scoped>
.auth-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #0d1027;
}

.auth-box {
  width: 100%;
  height: 800px; /* 增加整体高度 */
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
}

.auth-content {
  width: 100%;
  max-width: 1500px; /* 增加最大宽度 */
  display: flex;
  justify-content: space-between;
  gap: 100px; /* 加大左右两边的间距 */
  align-items: stretch;
  padding: 20px;
  box-sizing: border-box;
}

.left-section {
  flex: 1;
  padding: 0;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.right-section {
  width: 430px;
  background: rgba(30, 41, 77, 0.8);
  border-radius: 12px;
  padding: 25px;
  display: flex;
  flex-direction: column;
  align-self: stretch;
  margin: 0;
  height: 610px; /* 再次增加右侧区域固定高度 */
}

.auth-header {
  color: #fff;
  margin-bottom: 50px;
}

.auth-header h1 {
  font-size: 46px;
  margin-bottom: 20px;
  font-weight: 500;
}

.auth-header p {
  font-size: 20px;
  opacity: 0.8;
}

.features {
  display: flex;
  flex-direction: column;
  gap: 48px;
}

.feature-item {
  display: flex;
  align-items: center;
  background: rgba(30, 41, 77, 0.8);
  border-radius: 12px;
  padding: 22px 25px;
  color: #fff;
  margin-bottom: 5px;
}

.icon-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 46px;
  height: 46px;
  margin-right: 20px;
  color: #3080ff;
}

.feature-item .el-icon {
  font-size: 30px;
}

.feature-text {
  flex: 1;
}

.feature-item h3 {
  margin: 0 0 10px 0;
  font-size: 20px;
  font-weight: 500;
}

.feature-item p {
  margin: 0;
  opacity: 0.7;
  font-size: 16px;
  line-height: 1.6;
}

.tabs {
  display: flex;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  margin-bottom: 25px;
}

.tab {
  padding: 15px 30px;
  color: rgba(255, 255, 255, 0.7);
  cursor: pointer;
  font-size: 18px;
}

.tab.active {
  color: #3080ff;
  border-bottom: 2px solid #3080ff;
}

.form-outer-container {
  height: 480px; /* 固定容器高度 */
  position: relative;
  overflow: hidden;
}

.auth-form {
  color: #fff;
  position: absolute;
  width: 100%;
  top: 0;
  left: 0;
}

.login-form .form-item,
.register-form .form-item {
  margin-bottom: 20px;
  height: 85px; /* 统一登录和注册表单的输入框区域高度 */
}

.forgot-password-form .form-item {
  margin-bottom: 2px; /* 忘记密码表单的间距增加2px */
  height: 85px;
}

.form-item label {
  display: block;
  margin-bottom: 10px;
  font-size: 16px;
  color: rgba(255, 255, 255, 0.8);
}

/* 确保所有输入框高度一致 */
.form-item .el-input {
  height: 46px;
}

.form-item .el-input__wrapper {
  height: 46px;
  box-sizing: border-box;
}

.remember-me {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
}

.forgot-password {
  color: #3080ff;
  text-decoration: none;
  font-size: 14px;
}

.submit-button {
  width: 100%;
  height: 46px;
  font-size: 18px;
  background: #3080ff;
  border: none;
  margin-top: 15px;
  margin-bottom: 30px;
  border-radius: 6px;
}

.reset-tip {
  margin-bottom: 20px;
}

.reset-tip p {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.7);
  line-height: 1.5;
  text-align: center;
}

.back-to-login {
  text-align: center;
  margin-top: 15px;
}

.back-to-login a {
  color: #3080ff;
  text-decoration: none;
  font-size: 14px;
}

.back-to-login a:hover {
  text-decoration: underline;
}

.verification-code-item {
  margin-bottom: 20px;
}

.verification-code-input {
  display: flex;
  gap: 10px;
}

.verification-code-input .el-input {
  flex: 1;
}

.send-code-button {
  width: 120px;
  height: 46px;
  white-space: nowrap;
}

.verification-dialog-content {
  padding: 20px 0;
}

.verification-input {
  width: 100%;
  margin-bottom: 15px;
}

.verification-tip {
  text-align: center;
  color: #909399;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-dialog) {
  border-radius: 8px;
  background: #1e294d;
}

:deep(.el-dialog__title) {
  color: #fff;
  font-size: 18px;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  padding: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.el-dialog__body) {
  padding: 0 20px;
  color: #fff;
}

:deep(.el-dialog__footer) {
  padding: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.el-input__wrapper) {
  background-color: rgba(40, 50, 88, 0.8);
  box-shadow: none;
  border: 1px solid rgba(255, 255, 255, 0.1);
  height: 46px;
  border-radius: 6px;
  box-sizing: border-box;
}

:deep(.el-input__inner) {
  color: #fff;
  height: 46px;
  font-size: 16px;
  box-sizing: border-box;
}

:deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.4);
}

:deep(.el-checkbox__label) {
  color: rgba(255, 255, 255, 0.8);
  font-size: 16px;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #3080ff;
  border-color: #3080ff;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .auth-content {
    max-width: 1200px;
    gap: 60px;
  }
  
  .right-section {
    width: 400px;
  }

  .auth-header h1 {
    font-size: 36px;
  }

  .features {
    gap: 30px;
  }
}

@media (max-width: 1200px) {
  .auth-content {
    max-width: 1000px;
    gap: 40px;
  }
  
  .right-section {
    width: 380px;
  }

  .auth-header h1 {
    font-size: 34px;
  }

  .feature-item {
    padding: 16px;
  }

  .icon-container {
    width: 32px;
    height: 32px;
    margin-right: 14px;
  }

  .feature-item .el-icon {
    font-size: 22px;
  }

  .feature-item h3 {
    font-size: 17px;
  }

  .feature-item p {
    font-size: 13px;
  }

  .features {
    gap: 25px;
  }
  
  .submit-button {
    margin-bottom: 20px;
  }
}

@media (max-width: 992px) {
  .auth-content {
    flex-direction: column;
    align-items: center;
    max-width: 700px;
    gap: 40px;
  }
  
  .left-section {
    width: 100%;
    padding: 0;
  }
  
  .right-section {
    width: 100%;
    max-width: 500px;
  }

  .features {
    gap: 20px;
  }
}

@media (max-width: 576px) {
  .auth-container {
    padding: 15px;
  }
  
  .auth-header h1 {
    font-size: 28px;
  }
  
  .feature-item {
    padding: 14px;
  }
  
  .feature-item h3 {
    font-size: 16px;
  }
  
  .feature-item p {
    font-size: 13px;
  }
  
  .tab {
    padding: 10px 15px;
    font-size: 14px;
  }
  
  .form-item label {
    font-size: 14px;
  }
  
  :deep(.el-input__inner) {
    font-size: 14px;
  }

  .features {
    gap: 15px;
  }
  
  .submit-button {
    margin-bottom: 15px;
  }
}
</style>